#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import random
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from django.conf import settings
# from utils.tencent.msg import send_china_msg
# from utils.tencent.oss import get_credential
from ..serializers.auth import MessageCodeSerializer, LoginSerializer
from .. import models

from utils.encrypt import create_uid



class MessageView(APIView):
    """
    短信验证码
    """

    def get(self, request, *args, **kwargs):
        """
        获取用户手机号并发送短信，如果超出范围则返回提示信息。
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        # 1. 验证手机格式
        # 2. 创建验证码
        # 3. 发送短信
        # 4. 保存到redis（设置超时时间为1分钟）
        ser = MessageCodeSerializer(data=request.query_params)
        if not ser.is_valid():
            return Response({"status": False, "message": "验证码格式错误"})

        phone = ser.validated_data.get('phone')
        # result = send_china_msg(phone, random_code)
        # if not result.status:
        #     return Response({"status": False, "message": "验证码发送失败"})

        conn = get_redis_connection()
        redis_code = conn.get(phone)
        if redis_code:
            # 如果查到,则代表刚刚获取过不能再次获取
            return Response({"status": False, "message": "已获取过验证码"})
        # 模拟发送成功和失败，只有发送成功才生成验证码，进而存入redis
        # 如果发送失败，直接返回提示
        simulation = random.choice([True, False])
        if not simulation:
            print("验证码发送失败")
            return Response({"status": False, "message": "验证码发送失败"})

        random_code = random.randrange(1000, 9999)

        conn.set(phone, random_code, ex=60)
        print("生成验证码为：", random_code)
        return Response({"status": True, 'message': '验证码发送成功', "fourNum": random_code})

# 退出
class LogoutView(APIView):
    '''
    退出登录功能
    '''

    def post(self, request, *args, **kwargs):
        # 传入的token
        token = request.data.get('token', '')
        phone = request.data.get('phone', '')
        if not token:
            return Response({"status": False, "message": "退出登录失败"})
        # 去数据库里
        data_token = models.UserInfo.objects.filter(token=token).first()
        data_token = data_token.token
        if token != data_token:
            return Response({"status": False, "message": "退出登录失败"})
        conn = get_redis_connection()
        # 成功退出时，清掉redis中的验证码，以便用户能登录成功后马上退出再次重新获取验证码
        conn.delete(phone)
        return Response({"status": True, "message": "已成功退出"})


class LoginView(APIView):

    def post(self, request, *args, **kwargs):
        """ 用户登录接口 """

        # ########################## 线上正式操作 ##########################

        # 1. 校验用户输入的合法性
        ser = LoginSerializer(data=request.data)
        if not ser.is_valid():
            return Response({"status": False, 'detail': ser.errors, 'message': "验证码错误"})

        # 2. 获取微信session_key和openid
        #    https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
        wx_code = ser.validated_data.pop('wx_code')
        params = {
            'appid': settings.APPID,
            'secret': settings.SECRET,
            'js_code': wx_code,
            'grant_type': 'authorization_code'

        }
        result_dict = requests.get('https://api.weixin.qq.com/sns/jscode2session', params=params).json()
        ser.validated_data.pop('code')
        # 3.创建或更新账户
        phone = ser.validated_data.pop('phone')
        token = create_uid(phone)
        exists = models.UserInfo.objects.filter(telephone=phone).exists()
        # 粉丝个数，新注册肯定是0
        fans_count = 0
        # 关注个数，新注册肯定是0
        follow = 0
        if not exists:
            user_object = models.UserInfo.objects.create(**{**ser.validated_data, **result_dict}, token=token, telephone=phone)
            message = "注册成功"
            user_id = user_object.id
        else:
            user_object = models.UserInfo.objects.filter(telephone=phone)
            user_object.update(**{**ser.validated_data, **result_dict}, token=token)
            message = "登录成功"
            user_id = user_object.first().id
            fans_count = user_object.first().fans_count
            # 多对多母表查询子表，查找当前登录用户关注了哪些用户，也可以存放关注用户的相关信息，可参考浏览用户记录
            follow = models.UserInfo.objects.filter(follow__id=user_id).count()

            # 4.给用户返回相应信息
        data = {'token': token, 'phone': phone, "user_id": user_id,"fans_count":fans_count,"follow":follow}
        return Response({'status': True, "message": message, 'data': data})

        # ########################## 临时操作 ##########################
        # 1. 获取微信session_key和openid
        #    https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html

        # wx_code = request.data.get('wx_code')
        # params = {
        #     'appid': settings.APPID,
        #     'secret': settings.SECRET,
        #     'js_code': wx_code,
        #     'grant_type': 'authorization_code'
        #
        # }
        # result_dict = requests.get('https://api.weixin.qq.com/sns/jscode2session', params=params).json()
        #
        # # 2. 创建或更新账户
        # phone = request.data.get('phone')
        # token = create_uid(phone)
        # user_object = models.UserInfo.objects.filter(telephone=phone).first()
        # if not user_object:
        #     user_obj = models.UserInfo.objects.create(
        #         **result_dict,
        #         token=token,
        #         telephone=phone,
        #         nickname=request.data.get('nickName'),
        #         avatar=request.data.get('avatarUrl'),
        #     )
        #     message = "注册成功"
        # else:
        #     user_obj = models.UserInfo.objects.filter(telephone=phone).update(
        #         **result_dict,
        #         token=token,
        #         nickname=request.data.get('nickName'),
        #         avatar=request.data.get('avatarUrl')
        #     )
        #     message = "登录成功"
        #
        # # 3.给用户返回相应信息
        # data = {'token': token, 'phone': phone, "user_id":user_obj.id}
        # return Response({'status': True, "message": message, 'data': data})


# 腾讯对象存储 COS 使用临时密钥服务
# class OssCredentialView(APIView):
#     def get(self, request, *args, **kwargs):
#         return Response(get_credential())
